/**
 * create by young (young2f@outlook.com) on 2020/8/18
 */


'use strict';
import React, {Component} from 'react';
import styles from './index.less';
import {Button, Col, Form, Icon, Input, Row} from 'antd';
import {ModalView} from 'antd-extra';
//import ModalEditDLabel from "./modal/ModalEditDLabel";
import ModalDLabel from './modal/ModalDLabel';
import ViewTitle from '../ViewTitle';

const _ = require('lodash');

class DynamicLabel extends Component {
  constructor(props) {
    super(props);

  }

  changeKey = (key, e) => {
    const value = e.target.value;
    const { templateConfigData } = this.state;
    if (templateConfigData) {
      templateConfigData.forEach(obj => {
        if (obj.key === key) {
          Object.assign(obj, {
            key: key.substr(0, 15) + value,
            keyDefaultValue: value,
          });
          return false;
        }
      });

      this.setState({ templateConfigData });
    }
  };
  editItemCallback = (index, data) => {
    const { list } = this.props;
    const temp = list[index];
    const temp1 = _.assign(temp, data);
    list[index] = temp1;

    list.map((data) =>
      this.setFormItemValues(data),
    );
  };
  editItem = (item, index) => {

    const { form } = this.props;
    const res = form.validateFields((err, values) => {

      if (err) {
        return err;
      }
      const { driveCfgNames, driveCfgKeys, driveCfgTypes, driveCfgUrls, driveCfgSelectOptions, driveCfgRequireds, driveCfgPages, driveCfgDefaultValues } = values;

      for (let code in driveCfgNames) {
        if (code === item) {
          const key = driveCfgKeys[code];
          const label = driveCfgNames[code];
          const defaultValue = driveCfgDefaultValues[code];
          const type = driveCfgTypes[code];
          const url = driveCfgUrls[code];
          const required = driveCfgRequireds[code];

          const selectOption = driveCfgSelectOptions[code];
          const data = { label, code, key, defaultValue, selectOption, required, url, type };
          ModalView.open(ModalDLabel, { title: '编辑', width: '720px', height: '80%', noStore: true }, {
            index,
            data,
            result: this.editItemCallback,
          });
          return data;
        }
      }
    });
  };
  generateFormItem = (formItem, index) => {
    const { getFieldDecorator } = this.props.form;
    const { tabsCode } = this.props;
    const { code, key, label, type, url, defaultValue, selectOption, placeholder = '', required = true, regex } = formItem;
    // const code = `$${new Date().getTime()}$`

    return (
      <Row type="flex">
        <Col span={0}>
          <Form.Item>
            {getFieldDecorator(`driveCfgSelectOptions[${code}]`, { initialValue: selectOption })(
              <div>{selectOption}</div>,
            )}
          </Form.Item>
        </Col>
        <Col span={0}>
          <Form.Item>
            {getFieldDecorator(`driveCfgRequireds[${code}]`, { initialValue: required })(
              <div>{required}</div>,
            )}
          </Form.Item>
        </Col>
        <Col span={0}>
          <Form.Item>
            {getFieldDecorator(`driveCfgUrls[${code}]`, { initialValue: url })(
              <div>{url}</div>,
            )}
          </Form.Item>
        </Col>
        <Col span={0}>
          <Form.Item>
            {getFieldDecorator(`driveCfgTypes[${code}]`, { initialValue: type })(
              <div>{type}</div>,
            )}
          </Form.Item>
        </Col>
        <Col span={0}>
          <Form.Item>
            {getFieldDecorator(`driveCfgPages[${code}]`, { initialValue: tabsCode })(
              <div>{tabsCode}</div>,
            )}
          </Form.Item>
        </Col>
        <Col span={5}>
          <Form.Item>
            {getFieldDecorator(`driveCfgNames[${code}]`, {
              initialValue: label,
              // validateTrigger: ['onChange', 'onBlur'],
              rules: [{
                required: true,
                // whitespace: true,
                message: `请输入`,
              }],
            })(
              <Input placeholder={placeholder} style={{ width: '95%' }}/>,
            )}
          </Form.Item>
        </Col>

        <Col span={5}>
          <Form.Item>
            {getFieldDecorator(`driveCfgKeys[${code}]`, {
              initialValue: key,
              // validateTrigger: ['onChange', 'onBlur'],
              rules: [{
                required: required,
                // pattern: regex instanceof RegExp ? regex : eval(regex),
                message: '请输入',
              }],
            })(
              <Input placeholder="如 mode" style={{ width: '95%', marginRight: 2 }}/>,
            )}
          </Form.Item>
        </Col>
        <Col span={5}>
          <Form.Item>
            {getFieldDecorator(`driveCfgDefaultValues[${code}]`, {
              initialValue: defaultValue,
            })(
              <Input placeholder="默认值" style={{ width: '95%', marginRight: 2 }}/>,
            )}
          </Form.Item>
        </Col>
        <Col span={1}>
          <Form.Item>
            <Icon
              className={styles.dynamicDeleteButton}
              type="minus-circle-o"
              onClick={() => this.remove(`${code}`)}
            />
          </Form.Item>
        </Col>
        <Col span={1}>
          <Form.Item>
            <Icon
              className={styles.dynamicDeleteButton}
              type="edit"
              onClick={() => this.editItem(`${code}`, index)}
            />
          </Form.Item>
        </Col>
      </Row>);
  };
  setFormItemValues = (formItem) => {
    const { form } = this.props;
    const { code, key, label, type, url, defaultValue, selectOption, required = true } = formItem;
    let temp = `driveCfgNames[${code}]`;
    let json = {};
    json[temp] = label;
    form.setFieldsValue(json);

    temp = `driveCfgKeys[${code}]`;
    json = {};
    json[temp] = key;
    form.setFieldsValue(json);

    temp = `driveCfgDefaultValues[${code}]`;
    json = {};
    json[temp] = defaultValue;
    form.setFieldsValue(json);

    temp = `driveCfgRequireds[${code}]`;
    json = {};
    json[temp] = required;
    form.setFieldsValue(json);

    temp = `driveCfgUrls[${code}]`;
    json = {};
    json[temp] = url;
    form.setFieldsValue(json);

    temp = `driveCfgTypes[${code}]`;
    json = {};
    json[temp] = type;
    form.setFieldsValue(json);

    temp = `driveCfgSelectOptions[${code}]`;
    json = {};
    json[temp] = selectOption;
    form.setFieldsValue(json);
  };
  generateFormItems = () => {
    const { list } = this.props;
    if (!list || !list.length) {
      return null;
    }
    if (list) {
      let map = list.map((data, index) =>
        this.generateFormItem(data, index),
      );
      return map;
    }
    return null;
  };
  remove = (id) => {
    const { dataId, onChange, list } = this.props;
    if (list) {
      const temp = list.filter(obj => `${obj.code}` !== id);
      onChange(dataId, temp);
    }
  };
  addLabel = () => {
    let { dataId, onChange, list } = this.props;
    this.props.form.validateFields(['driveCfgPages', 'driveCfgKeys', 'driveCfgNames'], (err, values) => {
      if (!err) {
        if (!list) {
          list = [];
        }
        list.push({
          code: `$${new Date().getTime()}$`,
          required: true,
          type: 'Input',
        });
        onChange(dataId, list);
      }
    });
  };
  onSubmit = () => {
    const { tabsCode, treeId, dataId, tenantCode, page } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { driveCfgNames, driveCfgKeys, driveCfgTypes, driveCfgUrls, driveCfgSelectOptions, driveCfgRequireds, driveCfgPages, driveCfgDefaultValues } = values;
        const driveCfgs = [];
        for (let code in driveCfgNames) {
          const pageTemp = driveCfgPages[code];
          if (pageTemp === tabsCode) {
            const key = driveCfgKeys[code];
            const label = driveCfgNames[code];
            const defaultValue = driveCfgDefaultValues[code];
            const type = driveCfgTypes[code];
            const url = driveCfgUrls[code];
            const required = driveCfgRequireds[code];
            const selectOption = driveCfgSelectOptions[code];

            const data = {
              tenantCode,
              label,
              code,
              key,
              defaultValue,
              selectOption,
              treeId,
              required,
              url,
              type,
              page,
              tabsCode,
            };

            driveCfgs.push(data);
          }
        }
        const { onSubmit } = this.props;

        onSubmit(driveCfgs, dataId, treeId);
      }
    });
  };

  /**
   * props:
   * form、dataId
   * @returns {*}
   */
  render() {
    return (
      <div style={{ marginTop: '22px', width: '90%', marginLeft: '50px' }}>
        {<ViewTitle
          title={'配置项列表'}
        >
        </ViewTitle>}
        <Row type="flex">
          <Col span={5}>配置值名称</Col>
          <Col span={5}>配置项数据字段</Col>
          <Col span={5}>配置项默认值</Col>
          <Col span={1}>删除 </Col>
          <Col span={1}>编辑</Col>
        </Row>
        {this.generateFormItems()}
        {
          <Form.Item>
            <span>
               <Button type="dashed" onClick={this.addLabel.bind(this)} style={{ width: '61.5%' }}>
              <Icon type="plus"/>添加
            </Button>
            </span>
            <span>
           <Button type="primary" onClick={this.onSubmit.bind(this)}
                   style={{ marginLeft: '12px' }}>提 交</Button>
            </span>
          </Form.Item>
        }
      </div>
    );
  }
}

export default DynamicLabel;
